import json
from bson.objectid import ObjectId
from datetime import datetime
import time
import database
import traceback
import MySQLdb
import CONSTANTS
import config
#------------------------------------------------------------------------------
object_fields = ('type', 'content_type', 'from', 'message', 'url_img', 'money', 'expire_date', 'other_hint', 'broadcast', 'broadcast_message', 'broadcast_shortcut', 'msg_mail', 'metadata')


class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        return json.JSONEncoder.default(self, o)


class NotiInapp:
    def __init__(self):
        self.redis_conn = database.cache()._re_local.re_lc
#         self.mysql  = database.cache()._handlemysql.mysql

    def call_proce(self, fuc, args):
        results = 0
        try:
            while True:
                try:
                    v_mysql = MySQLdb.connect(host=config.MYSQL_HOST, port=config.MYSQL_PORT, user=config.MYSQL_USER, passwd=config.MYSQL_PASS, db=config.MYSQL_DB, charset='utf8')
                    v_cursor = v_mysql.cursor()
                    break
                except:
                    traceback.print_exc()
                time.sleep(1)
            v_cursor.callproc(fuc, args)
            results = v_cursor.fetchall()
            v_cursor.close()
            v_mysql.commit()
            v_mysql.close()
        except:
            traceback.print_exc()
        return results

    def get_waiting_task(self):
        """
        get 1 task from redis list(redis local)
        """
        v_task = self.redis_conn.lpop(CONSTANTS.LOCAL_RD.TASKS)
        if not v_task: 
            return None
        return eval(v_task)

    def rt_login(self, i_job, args):
        """
        call produce in mysql
        """
        try:
            app_name = i_job.split(':')[0]
            platform = args.get('platform', '')
            username = args.get('username', '')
            token = args.get('token', '')
            create_time = args.get('create_time', int(time.time()))
            lastlogin = args.get('lastlogin', int(time.time()))
            if token:
                argssql = (CONSTANTS.app_name2id[app_name.lower()], platform, username, token, create_time, lastlogin)
                self.call_proce('login', argssql)
            else:
                return '0:token is empty'
        except:
            return '0:error while communicating with mysql server'

    def rt_logout(self, i_job, args):
        try:
            app_name = i_job.split(':')[0]
            username = args.get('username', '')
            lastactive = args.get('lastactive', '')
            argssql = (CONSTANTS.app_name2id[app_name.lower()], username, lastactive)
            self.call_proce('logout', argssql)
        except:
            return '0:error while communicating with mysql server'

    def rt_inapp_noti(self, i_job, args):
        try:
            app_id = args.get('app_id')
            user_name = args.get('user_name').strip()
            message = args.get('message')
            
            create_time = args.get('create_time', int(time.time()))
            status = args.get('status', 1)
            #------- TODO type:string
            v_type = args.get('type', 0)
            content_type = args.get('content_type', 3)
            v_from = args.get('from', 'iOnline')
            url_img = args.get('url_img', '')
            money = args.get('money', 0)
            expire_date = args.get('expire_date', None)
            other_hint = args.get('other_hint', '[\"\",\"\"]')
            broadcast = args.get('broadcast', True)
            broadcast_message = args.get('broadcast_message', '[\"\",\"\"]')
            broadcast_shortcut = args.get('broadcast_shortcut', 'http://ionline.com.vn/sukien')
            msg_mail = args.get('msg_mail', '[\"\",\"\"]')
            metadata = args.get('metadata', None)
            
            v_object = dict(zip(object_fields, (v_type, content_type, v_from, message, url_img, money, expire_date, other_hint, broadcast, broadcast_message, broadcast_shortcut, msg_mail, metadata)))
            v_object = json.dumps(v_object)
            argssql = (app_id, user_name, v_object, create_time, status)
            self.call_proce('set_inapp_noti', argssql)
        except:
            traceback.print_exc()

    def rt_set_token(self, args):
        try:
            argssql = (args['app_id'], args['platform'], args['user_id'], args['token'], args['create_time'])
            self.call_proce('set_token', argssql)
        except:
            return '0:error while communicating with mysql server'
#------------------------------------------------------------------------------ 
    functions = {
        'ionline:login': rt_login,
        'ionline:logout': rt_logout,
        'ico:login': rt_login,
        'inappnoti': rt_inapp_noti,
        4: rt_set_token
    }

    def rt_all(self, i_task):
        if i_task.has_key('job'):
#             print 'task:',i_task
            v_paras = i_task['params']
            v_job = i_task['job']
            func = NotiInapp.functions[v_job]
#             v_task['app_name'] = v_job.split(':')[0]
            func(self, v_job, v_paras)
            print 'done task', i_task
#------------------------------------------------------------------------------ 